package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.scribe.builder.api.FacebookApi;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import repository.SearchRepository;
import repository.UserRepository;
import util.ApiClientBuilder;
import util.CSVReader;
import util.EmailSender;
import util.FacebookMatchHelper;
import util.LinkedInMatchHelper;
import util.MailTitleBody;
import util.MailTitleBody.MailTitleBodyEnum;
import util.OAuthServiceConfig;
import util.OAuthServiceProvider;
import validator.MassiveImportFormValidator;
import validator.SearchProfileFormValidator;

import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.enumeration.ProfileField;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
import com.restfb.DefaultFacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookException;
import com.restfb.exception.FacebookGraphException;
import com.restfb.exception.FacebookJsonMappingException;
import com.restfb.exception.FacebookNetworkException;
import com.restfb.exception.FacebookOAuthException;
import com.restfb.exception.FacebookResponseStatusException;
import com.restfb.json.JsonObject;
import command.EditResultForm;
import command.MassiveImportForm;
import command.MassiveSaveForm;
import command.SearchProfileForm;

import domain.FacebookProfile;
import domain.FacebookUser;
import domain.File;
import domain.SearchResultItem;
import domain.SearchResultList;
import domain.SocialToken;
import domain.User;
import domain.exceptions.DuplicateException;

@Controller
public class DataController {

	private UserRepository userRepository;
	private MassiveImportFormValidator massiveFormValidator;
	private SearchProfileFormValidator searchProfileFormValidator;
	private SearchRepository searchRepository;
	private LinkedInApiClientFactory factory;
	private LinkedInApiClient client;
	private DefaultFacebookClient facebookClient;
	private LinkedInOAuthService oauthService;
	private OAuthServiceProvider facebookOauthservice;
	private LinkedInMatchHelper linkedInMatchHelper;
	private FacebookMatchHelper facebookMatchHelper;
	private final String LINKEDIN_API_KEY = "rnaeme79uqz5";
	private final String LINKEDIN_API_SECRET = "nz5A3kPcwP0yzkfs";
	private final String FACEBOOK_API_KEY = "429147717173757";
	private final String FACEBOOK_API_SECRET = "3d822d5a2feda7a4dc390cb3e0ced38f";
	private final Token EMPTY_TOKEN = null;
	private MessageSource msgSrc;

	@Autowired
	public DataController(UserRepository userRepository,
			MassiveImportFormValidator massiveFormValidator,
			SearchRepository searchRepository, LinkedInMatchHelper linkedInMatchHelper,
			FacebookMatchHelper facebookMatchHelper,
			SearchProfileFormValidator searchProfileFormValidator,
			MessageSource msgSrc) {
		this.userRepository = userRepository;
		this.massiveFormValidator = massiveFormValidator;
		this.searchProfileFormValidator = searchProfileFormValidator;
		this.searchRepository = searchRepository;
		this.linkedInMatchHelper = linkedInMatchHelper;
		this.facebookMatchHelper = facebookMatchHelper;
		this.msgSrc = msgSrc; 
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView ListSavedResults(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<SearchResultList> results = this.searchRepository
				.getSavedResultsByUser(user);
		ModelAndView mav = new ModelAndView("data/ListSavedResults");
		mav.addObject("results", results);
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView ViewSavedResult(
			@RequestParam("result_id") SearchResultList list) {
		List<SearchResultItem> results = list.getResults();
		ModelAndView mav = new ModelAndView();
		String emails = "";
		for (int i = 0; i < results.size(); i++) {
			emails += results.get(i).getUser().getEmail()
					+ (i == results.size() - 1 ? "" : ",");
		}
		mav.addObject("emails", emails);
		mav.addObject("results", list);
		mav.addObject("massiveSaveForm", new MassiveSaveForm());
		mav.setViewName("data/ViewSavedResult");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView DeleteSavedResult(HttpSession session,
			@RequestParam("result_id") SearchResultList list) {
		this.searchRepository.deleteSavedResult(list);
		return ListSavedResults(session);
	}

	@RequestMapping(method = RequestMethod.GET)
	protected String FlagResult(
			@RequestParam("result_item_id") SearchResultItem item,
			@RequestParam("flag") boolean flag,
			@RequestParam("result_id") int resultId) {
		item.setFlagged(flag);
		return "redirect:../user/viewResult?resultId=" + item.getId()
				+ "&searchResultId=" + resultId;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView NewSearchProfile() {
		ModelAndView mav = new ModelAndView("data/NewSearchProfile");
		mav.addObject("searchProfileForm", new SearchProfileForm());
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST)
	protected ModelAndView NewSearchProfile(HttpSession session,
			SearchProfileForm form, Errors errors) {
		ModelAndView mav = new ModelAndView();
		User userlogged = (User) session.getAttribute("user");
		searchProfileFormValidator.validate(form, errors);
		if (errors.hasErrors()) {
			return mav;
		}
		SearchResultList profile = new SearchResultList(userlogged,
				form.getName(), form.getDescription());
		searchRepository.saveResults(profile);
		return ListSavedResults(session);
	}

	@RequestMapping(method = RequestMethod.POST)
	public String editResult(EditResultForm form,
			@RequestParam("resultId") SearchResultItem result,
			@RequestParam("results_id") int resultId) {
		result.setComment(form.getComment());
		return "redirect:../user/viewResult?resultId=" + result.getId()
				+ "&searchResultId=" + resultId + "#comentarios";
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView SaveActions(MassiveSaveForm form, Errors errors,
			HttpSession session,
			@RequestParam("profileId") SearchResultList profile,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("user/ListUsers");
		User userlogged = (User) session.getAttribute("user");
		mav.addObject("profiles",
				searchRepository.getSavedResultsByUser(userlogged));
		mav.addObject("users", form.getUsers());
		if (form.getUsersSelected() == null) {
			errors.rejectValue("usersSelected", "saveNoUserError");
			return mav;
		}
		if (request.getParameter("save") != null) {
			profile.addResults(form.getUsersSelected());
			return mav;
		} else if (request.getParameter("delete") != null) {
			profile.removeResults(form.getUsersSelected());
			return ViewSavedResult(profile);
		} else {
			return exportUsers(mav, response, form, errors);
		}
	}

	private ModelAndView exportUsers(ModelAndView mav,
			HttpServletResponse response, MassiveSaveForm form, Errors errors) {
		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		response.setContentType("application/csv");
		response.setHeader("content-disposition", "filename=ALUMNIExport-"
				+ sdf.format(today) + ".csv");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.write("document number, first name, last name, main email, student code, birthdate, phones, personal emails\n");
			for (User u : form.getUsersSelected()) {
				out.write(u.toCSV());
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			errors.rejectValue("usersToExport", "exportFileError");
			mav.addObject("users", form.getUsersSelected());
		}
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView ImportUsers() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("massiveImportForm", new MassiveImportForm());
		mav.setViewName("data/ImportUsers");
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView ImportUsers(HttpSession session,
			MassiveImportForm form, Errors errors) {
		List<User> users = new ArrayList<User>();
		int rejected = 0;
		List<String> rejectedList = new ArrayList<String>();
		ModelAndView mav = new ModelAndView();
		massiveFormValidator.validate(form, errors);
		if (errors.hasErrors()) {
			return mav;
		}

		String subtitle = "";
		int i = 0;
		try {
			File file = new File(form.getFilename().getBytes());
			users = CSVReader.importUsers(file);
			String[] emails = new String[users.size()];
			String[] pass = new String[users.size()];
			for (User user : users) {
				try {
					userRepository.newUser(user);
					emails[i] = user.getEmail();
					pass[i++] = user.getPassword();
				} catch (DuplicateException e) {
					rejected++;
					rejectedList.add(user.getDocNumber());
				}
			}
			if (i > 0) {
				MailTitleBody mtb = MailTitleBodyEnum.IMPORTED_USER.getTitleAndBody();
				mtb.appendPasses(pass);
				new EmailSender(emails, mtb).start();
			}
			if (rejectedList.size() > 0) {
				errors.rejectValue("filename", "importDup");
			}
		} catch (Exception e) {
			errors.rejectValue("filename", "parseError");
			subtitle = e.getMessage();
			mav.addObject("errorLogin", subtitle);
		}
		String error = "";
		if (errors.hasErrors()) {
			error = "Hubo un error en la importaci&oacute;n. ";
			if (rejectedList.size() > 0) {
				error += "Algunos de los documentos o e-mails en el archivo ya existen en nuestra base. <br />";
				error += "<b>Usuarios NO importados: " + rejectedList.size() + ".</b><br />";
				error += "N&uacute;meros de documento de usuarios en conflicto: <br /><ul>";
				for (String docNum: rejectedList) {
					error += "<li>" + docNum + " </li>";
				}
				error += "</ul>";
			}
		}
		String title = "<b>No se ha importado ning&uacute;n usuario. </b>";
		if (users.size() > rejectedList.size()) {
			title = "<b>Se ha(n) importado " + (users.size() - rejected) + " usuario(s) correctamente. </b>";
		}
		mav.addObject("messages", error + title);
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView connectLinkedIn(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		User userlogged = (User) session.getAttribute("user");
		User user = userRepository
				.getUserByDocNumber(userlogged.getDocNumber());
		SocialToken socialToken = user.getSocialToken();

		if (socialToken != null && socialToken.getLinkedInToken() != null) {
			LinkedInAccessToken accessToken = new LinkedInAccessToken(
					socialToken.getLinkedInToken(),
					socialToken.getLinkedinTokenSecret());
			factory = LinkedInApiClientFactory.newInstance(LINKEDIN_API_KEY,
					LINKEDIN_API_SECRET);
			client = factory.createLinkedInApiClient(accessToken);
			try {
				client.getProfileForCurrentUser();
				// if we are here, tokens still work, so no need to ask user
				// for permission.
				mav.setViewName("data/gotPermissionsForLinkedIn");
				return mav;
			} catch (LinkedInApiClientException e) {
				// if we got here, it means old tokens dont work anymore, so
				// we ask them again
			}
		}
		mav.setViewName("data/getPermissionLinkedIn");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected String signInLinkedIn(HttpSession session) {
		oauthService = LinkedInOAuthServiceFactory.getInstance()
				.createLinkedInOAuthService(LINKEDIN_API_KEY,
						LINKEDIN_API_SECRET);
		// TODO sacar url
		LinkedInRequestToken requestToken = oauthService
				.getOAuthRequestToken("http://tommyalvarez.lvh.me:8081/Alumni/bin/data/signedInLinkedIn.jsp");
		String authUrl = requestToken.getAuthorizationUrl();
		session.setAttribute("requestToken", requestToken);
		return ("redirect:" + authUrl);
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView signedInLinkedIn(HttpSession session,
			HttpServletRequest request) {
		String oauthVerifier = request.getParameter("oauth_verifier");
		User userlogged = (User) session.getAttribute("user");
		if (oauthVerifier != null) {
			LinkedInRequestToken requestToken = (LinkedInRequestToken) session
					.getAttribute("requestToken");
			LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(
					requestToken, oauthVerifier);

			factory = LinkedInApiClientFactory.newInstance(LINKEDIN_API_KEY,
					LINKEDIN_API_SECRET);
			client = factory.createLinkedInApiClient(accessToken);

			User user = userRepository.getUserByDocNumber(userlogged
					.getDocNumber());

			if (user.getSocialToken() == null) {
				user.setSocialToken(new SocialToken());
			}

			user.getSocialToken().setLinkedinToken(accessToken.getToken());
			user.getSocialToken().setLinkedinTokensecret(
					accessToken.getTokenSecret());

			if (!user.isAdmin()) {
				Person person = client.getProfileForCurrentUser(EnumSet
						.allOf(ProfileField.class));
				user.getProfile().getLinkedInProfile()
						.setImportedProfile(person);
			}

			session.setAttribute("user", user);
		}

		if (userlogged.isAdmin()) {
			return new ModelAndView("redirect:../general/index");
		} else {
			return new ModelAndView("redirect:../user/viewProfile?userid="
					+ ((User) session.getAttribute("user")).getId());
		}
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView matchLinkedIn(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		User userlogged = userRepository.getUser(((User) session
				.getAttribute("user")).getId());
		List<User> users = userRepository.getRegularConfirmedUsers();
		ApiClientBuilder apiClientBuilder = new ApiClientBuilder();

		if (apiClientBuilder.buildLinkedInApiClient(userlogged,
				LINKEDIN_API_KEY, LINKEDIN_API_SECRET)) {
			try {
				linkedInMatchHelper.match(apiClientBuilder, users);
			} catch (LinkedInApiClientException e) {
				if (e.getCause() != null && e.getCause().getClass().equals(UnknownHostException.class)) {
					mav.addObject("errorLogin", msgSrc.getMessage("errorConexionLinkedin", null,null));
				} else {
					// Usually when api call limit per day is reached
					mav.addObject("errorLogin", msgSrc.getMessage("errorLimiteLinkedin", null,null));
				}
			}
		} else {
			mav.addObject(
					"errorLogin",
					"Debe conceder permiso de acceso a LinkedIn haciendo click <a href='../data/signInLinkedIn'>aqu&iacute;</a>");
		}
		mav.addObject("matchedProfiles",
				linkedInMatchHelper.getMatchedProfiles());
		mav.addObject("conflictedProfiles",
				linkedInMatchHelper.getConflictedProfiles());
		mav.addObject("unmatchedProfiles",
				linkedInMatchHelper.getUnmatchedProfiles());
		mav.setViewName("data/matchedLinkedInResults");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView matchedLinkedInResults(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("matchedProfiles",
				linkedInMatchHelper.getMatchedProfiles());
		mav.addObject("conflictedProfiles",
				linkedInMatchHelper.getConflictedProfiles());
		mav.addObject("unmatchedProfiles",
				linkedInMatchHelper.getUnmatchedProfiles());
		mav.setViewName("data/matchedLinkedInResults");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView solveConflict(HttpSession session,
			@RequestParam("userid") User conflictedUser) {
		ModelAndView mav = new ModelAndView();
		List<Person> matchedProfiles = null;

		matchedProfiles = linkedInMatchHelper.getConflicts()
				.get(conflictedUser);
		mav.addObject("matchedLinkedInProfiles", matchedProfiles);
		mav.addObject("conflictedProfile", conflictedUser.getProfile());
		mav.setViewName("data/solveConflict");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView assignLinkedInProfile(HttpSession session,
			@RequestParam("userid") User resolvedUser,
			@RequestParam("linkedInId") String linkedInId) {
		ModelAndView mav = new ModelAndView();

		linkedInMatchHelper.resolveCandidate(resolvedUser, linkedInId);

		mav.addObject("resolvedUser", resolvedUser);
		mav.addObject("assignedProfile", resolvedUser.getProfile()
				.getLinkedInProfile());
		mav.addObject("messages", msgSrc.getMessage("conflictoResuelto", null,null));

		return matchedLinkedInResults(session);
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView connectFacebook(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		User userlogged = (User) session.getAttribute("user");
		User user = userRepository
				.getUserByDocNumber(userlogged.getDocNumber());
		SocialToken socialToken = user.getSocialToken();

		if (socialToken != null && socialToken.getFacebooktoken() != null) {
			facebookClient = new DefaultFacebookClient(socialToken.getFacebooktoken());
			try {
				facebookClient.fetchObject("me", FacebookUser.class);
				// if we are here, tokens still work, so no need to ask user
				// for permission.
				mav.setViewName("data/gotPermissionsForFacebook");
				return mav;
			} catch (FacebookOAuthException e) {
				// if we got here, it means old tokens dont work anymore, so
				// we ask them again
			}
		}
		mav.setViewName("data/getPermissionFacebook");
		return mav;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	protected String signInFacebook(HttpSession session) {
		OAuthServiceConfig config = new OAuthServiceConfig(
				FACEBOOK_API_KEY,
				FACEBOOK_API_SECRET,
				"http://tommyalvarez.lvh.me:8081/Alumni/bin/data/signedInFacebook",
				FacebookApi.class);

		facebookOauthservice = new OAuthServiceProvider(config);

		String authUrl = facebookOauthservice.getService().getAuthorizationUrl(
				EMPTY_TOKEN);
		session.setAttribute("fbrequestToken", EMPTY_TOKEN);
		return ("redirect:" + authUrl);
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView signedInFacebook(HttpSession session,
			HttpServletRequest request) {
		User userlogged = (User) session.getAttribute("user");
		Verifier v = new Verifier(request.getParameter("code"));
		if (v != null) {
			Token requestToken = (Token) session.getAttribute("fbrequestToken");
			Token accessToken = facebookOauthservice.getService()
					.getAccessToken(requestToken, v);

			User user = userRepository.getUserByDocNumber(userlogged.getDocNumber());

			if (user.getSocialToken() == null) {
				user.setSocialToken(new SocialToken());
			}

			user.getSocialToken().setFacebooktoken(accessToken.getToken());
			user.getSocialToken().setFacebooktokensecret(
					accessToken.getSecret());

			facebookClient = new DefaultFacebookClient(accessToken.getToken());

			if (!user.isAdmin()) {
				FacebookUser fbprofile = facebookClient.fetchObject("me", FacebookUser.class);
				JsonObject jsonPicture = facebookClient.fetchObject("me", JsonObject.class, Parameter.with("fields", "picture"));
				fbprofile.setPic(jsonPicture.getJsonObject("picture").getJsonObject("data").getString("url"));
				user.getProfile().setFacebookProfile(FacebookProfile.buildFacebookProfile(fbprofile));
			}

			session.setAttribute("user", user);
		}

		if (userlogged.isAdmin()) {
			return new ModelAndView("redirect:../general/index");
		} else {
			return new ModelAndView("redirect:../user/viewProfile?userid=" + ((User) session.getAttribute("user")).getId());
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView matchFacebook(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		User userlogged = userRepository.getUser(((User) session.getAttribute("user")).getId());
		List<User> users = userRepository.getRegularConfirmedUsers();
		ApiClientBuilder apiClientBuilder = new ApiClientBuilder();
		if (userlogged.getSocialToken() != null && userlogged.getSocialToken().getFacebooktoken() != null) {
			apiClientBuilder.buildFacebookClient(userlogged, FACEBOOK_API_KEY, FACEBOOK_API_SECRET);
			try {
				facebookMatchHelper.match(apiClientBuilder, users);
			} catch (FacebookJsonMappingException e) {
				// Looks like this API method didn't really return a list of users
				mav.addObject("errorLogin",msgSrc.getMessage("errorJsonMappingFacebook", null,null));
			} catch (FacebookNetworkException e) {
			  // An error occurred at the network level
				mav.addObject("errorLogin",msgSrc.getMessage("errorNetworkFacebook", null,null) + " " + e.getHttpStatusCode());
			} catch (FacebookOAuthException e) {
			  // Authentication failed - bad access token?
				mav.addObject("errorLogin",msgSrc.getMessage("errorFacebookOauth", null,null));
			} catch (FacebookGraphException e) {
			  // The Graph API returned a specific error
				mav.addObject("errorLogin",msgSrc.getMessage("errorGraphApiFacebook", null,null) + " " + e.getErrorMessage());
			} catch (FacebookResponseStatusException e) {
			  // Old-style Facebook error response.
			  // The Graph API only throws these when FQL calls fail.
			  // You'll see this exception more if you use the Old REST API
			  // via LegacyFacebookClient.
			  if (e.getErrorCode() == 200){
				  mav.addObject("errorLogin",msgSrc.getMessage("errorLegacyApi", null,null));  
			  }
			} catch (FacebookException e) {
			  // This is the catchall handler for any kind of Facebook exception
				mav.addObject("errorLogin",msgSrc.getMessage("errorFacebookGeneral", null,null));
			} catch (Exception e) {
				// Usually when api call limit per day is reached
				mav.addObject("errorLogin",msgSrc.getMessage("errorFacebookGeneric", null,null));
			}
		} else {
			mav.addObject("errorLogin", "Debe conceder permiso de acceso a facebook haciendo click <a href='../data/signInFacebook'>aqu&iacute;</a>");
		}
		mav.addObject("matchedProfiles",facebookMatchHelper.getMatchedProfiles());
		mav.addObject("conflictedProfiles", facebookMatchHelper.getConflictedProfiles());
		mav.addObject("unmatchedProfiles", facebookMatchHelper.getUnmatchedProfiles());
		mav.setViewName("data/matchedFacebookResults");
		return mav;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView matchedFacebookResults(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("matchedProfiles", facebookMatchHelper.getMatchedProfiles());
		mav.addObject("conflictedProfiles", facebookMatchHelper.getConflictedProfiles());
		mav.addObject("unmatchedProfiles", facebookMatchHelper.getUnmatchedProfiles());
		mav.setViewName("data/matchedFacebookResults");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView solveFacebookConflict(HttpSession session,
			@RequestParam("userid") User conflictedUser) {
		ModelAndView mav = new ModelAndView();
		List<FacebookUser> matchedProfiles = null;
		matchedProfiles = facebookMatchHelper.getConflicts().get(conflictedUser);
		mav.addObject("matchedFacebookProfiles", matchedProfiles);
		mav.addObject("conflictedProfile", conflictedUser.getProfile());
		mav.setViewName("data/solveFacebookConflict");
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView assignFacebookProfile(HttpSession session,
			@RequestParam("userid") User resolvedUser,
			@RequestParam("facebookId") String facebookId) {
		ModelAndView mav = new ModelAndView();
		boolean resolved = facebookMatchHelper.resolveCandidate(resolvedUser, facebookId);
		mav.addObject("resolvedUser", resolvedUser);
		mav.addObject("assignedProfile", resolvedUser.getProfile().getFacebookProfile());
		if (resolved) {
			mav.addObject("messages", "Se ha resuelto exitosamente el conflicto!");
		} else {
			mav.addObject("messages", "No se pudo asignar el perfil!");
		}
		return matchedFacebookResults(session);
	}
}
